package com.wg.core.serialize.impl;

import com.wg.core.io.BigEndianBinaryReader;
import com.wg.core.serialize.ISerializer;
import com.wg.core.io.IBinaryReadable;
import com.wg.core.io.IBinaryWritable;
import com.wg.core.serialize.SerializeType;

/**
 * 二进制序列化器
 *
 * <p>
 * 提供对象的二进制序列化和反序列化功能，支持基本类型、字符串、数组、集合和自定义可序列化对象。
 * </p>
 *
 * @author 少爷123
 */
public class BinarySerializer implements ISerializer {
    @Override
    public byte[] serialize(Object obj) {
        if (obj == null) return new byte[0];

        if (obj instanceof IBinaryWritable) {
            return ((IBinaryWritable) obj).toBytes();
        } else {
            throw new IllegalArgumentException("Unsupported type: " + obj.getClass());
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        if (data == null || data.length == 0) return null;

        BigEndianBinaryReader reader = new BigEndianBinaryReader(data);
        try {
            if (IBinaryReadable.class.isAssignableFrom(clazz)) {
                T instance = clazz.getDeclaredConstructor().newInstance();
                ((IBinaryReadable) instance).readBytes(reader);
                return instance;
            } else {
                throw new IllegalArgumentException("Unsupported type: " + clazz);
            }
        } catch (Exception e) {
            throw new RuntimeException("Deserialize error", e);
        }
    }

    @Override
    public int getType() {
        return SerializeType.BINARY.getType();
    }
}
